package simco.framework.gui.swing.comp;

import java.awt.Color;
import java.awt.Font;
import java.util.ResourceBundle;

import javax.swing.DefaultComboBoxModel;
import javax.swing.JColorChooser;
import javax.swing.JComboBox;
import javax.swing.JOptionPane;
import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.PlainDocument;

import simco.framework.gui.graph.supp.ViewModeType;
import simco.framework.gui.utils.Configuration;
import simco.framework.gui.utils.LocalizationUtil;

/**
* Tato trida deklaruje dialog pro nastavovani nekterych
* vlastnosti GUI ovlivnujici vzhledu.
* 
* @author Matej Prokop, mythge@students.zcu.cz
*/
public class VisualSettingsDialog extends javax.swing.JDialog 
{
	/**
	 * Tlaticko pro ulozeni nastaveni
	 */
	private javax.swing.JButton saveButton;
	
	/**
	 * Tlacitko pro nacteni defaultnich hodnot
	 */
	private javax.swing.JButton resetButton;
	
	/**
	 * Tlacitko pro zruseni
	 */
	private javax.swing.JButton cancelButton;
	
	/**
	 * Tlacitko pro vyber barvy oznaceni
	 */
	private javax.swing.JButton selectedColorButton;
	
	/**
	 * Tlacitko pro vyber barvy zvyrazneni
	 */
	private javax.swing.JButton markedColorButton;
	
	/**
	 * Combobox pro vyber defualtniho zobrazovaciho modu
	 */
	private javax.swing.JComboBox viewModeComboBox;
	
	/**
	 * Combobox pro vyber velikosti pisma
	 */
	private javax.swing.JComboBox fontSizeComboBox;
	
	// popisky:
	private javax.swing.JLabel eventsSettingTitle;
	private javax.swing.JLabel restartInfoLabel;
	private javax.swing.JLabel historyLengthLabel;
	private javax.swing.JLabel selectedColorLabel;
	private javax.swing.JLabel markedColorLabel;
	private javax.swing.JLabel canvasSettingTitle;
	private javax.swing.JLabel fontSizeLabel;
	private javax.swing.JLabel viewModeLabel;
	private javax.swing.JPanel innerPanel;
	private javax.swing.JTextField historyLengthTextField;
	
	/**
	 * Pismo pro vykresleni nadpisu
	 */
	private final Font titleFont = new Font("Tahoma", Font.BOLD, 14 );
	
	/**
	 * Pismo pro vykresleni normalniho textu
	 */
	private final Font normalFont = new Font("Tahoma", Font.PLAIN, 12 );
	
	/**
	 * Pismo pro vykresleni poznamek
	 */
	private final Font infoFont = new Font("Tahoma", Font.BOLD, 10 );
	
	/**
	 * Reference na objekt s nactenou lokalizaci
	 */
	private ResourceBundle locResource;
	
	/**
	 * Vybrana barva pro zvyrazeni objektu
	 */
	private Color tmpMarkColor = null;
	
	/**
	 * Vybrana barva pro vybraneho graficke objekty
	 */
	private Color tmpSelectColor = null;
	
	/**
	 * Vytvori novy dialog pro nastaveni vizualnich vlastnosti GUI.
	 * 
	 * @param parent reference nahlavni okno apliace
	 * @param modal log. promena jestli je diaglo modalni
	 */
   public VisualSettingsDialog(java.awt.Frame parent, boolean modal) 
   {
       super(parent, modal);
       
       this.locResource = LocalizationUtil.getResource(this.getClass().getSimpleName());
       
       tmpMarkColor = Configuration.getColorOfMarked();
       tmpSelectColor = Configuration.getColorOfSelected();
       
       setResizable(false);
       
       initComponents();
       
       pack();
       this.setLocationRelativeTo(parent);
   }
   
   /**
    * Inicializuje a rozmisti komponenty na dialogu
    */
   private void initComponents() 
   {
       innerPanel = new javax.swing.JPanel();
       eventsSettingTitle = new javax.swing.JLabel();
       markedColorLabel = new javax.swing.JLabel();
       restartInfoLabel = new javax.swing.JLabel();
       
       selectedColorButton = new javax.swing.JButton();
       saveButton = new javax.swing.JButton();
       viewModeComboBox = new javax.swing.JComboBox();
       canvasSettingTitle = new javax.swing.JLabel();
       historyLengthLabel = new javax.swing.JLabel();
       selectedColorLabel = new javax.swing.JLabel();
       resetButton = new javax.swing.JButton();
       markedColorButton = new javax.swing.JButton();
       cancelButton = new javax.swing.JButton();
       fontSizeLabel = new javax.swing.JLabel();
       viewModeLabel = new javax.swing.JLabel();
       fontSizeComboBox = new javax.swing.JComboBox();

       historyLengthTextField = new javax.swing.JTextField(new NumericDoc(4),
    		   "" + Configuration.getHistoryLength(), 1);
       
       setTitle(locResource.getString("dialog.title"));
       
       setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
       setName("Form"); // NOI18N

       innerPanel.setName("jPanel1"); // NOI18N

       eventsSettingTitle.setFont(titleFont); // NOI18N
       eventsSettingTitle.setText(locResource.getString("eventsSettingTitle.text")); // NOI18N
       eventsSettingTitle.setName("eventsSettingTitle"); // NOI18N

       markedColorLabel.setFont(normalFont); // NOI18N
       markedColorLabel.setText(locResource.getString("markedColorLabel.text")); // NOI18N
       markedColorLabel.setName("markedColorLabel"); // NOI18N

       restartInfoLabel.setFont(infoFont); // NOI18N
       restartInfoLabel.setText(locResource.getString("restartInfoLabel.text")); // NOI18N
       restartInfoLabel.setName("restartInfoLabel"); // NOI18N

       historyLengthTextField.setFont(normalFont); // NOI18N
       historyLengthTextField.setHorizontalAlignment(javax.swing.JTextField.RIGHT);
       historyLengthTextField.setName("historyLengthTextField"); // NOI18N

       selectedColorButton.setFont(normalFont); // NOI18N
       selectedColorButton.setText(locResource.getString("selectedColorButton.text")); // NOI18N
       selectedColorButton.setName("selectedColorButton"); // NOI18N
       selectedColorButton.addActionListener(new java.awt.event.ActionListener() 
       {
           public void actionPerformed(java.awt.event.ActionEvent evt) 
           {
           		chooseSelectColor();
           }
       });

       saveButton.setText(locResource.getString("saveButton.text")); // NOI18N
       saveButton.setName("saveButton");
       saveButton.addActionListener(new java.awt.event.ActionListener() 
       {
           public void actionPerformed(java.awt.event.ActionEvent evt) 
           {
           		saveBtnPressed();
           }
       });

       viewModeComboBox.setFont(normalFont); // NOI18N       
       viewModeComboBox.setName("viewModeComboBox"); // NOI18N
       setPossibleViewModes(viewModeComboBox);

       canvasSettingTitle.setFont(titleFont); // NOI18N
       canvasSettingTitle.setText(locResource.getString("canvasSettingTitle.text")); // NOI18N
       canvasSettingTitle.setName("canvasSettingTitle"); // NOI18N

       historyLengthLabel.setFont(normalFont); // NOI18N
       historyLengthLabel.setText(locResource.getString("historyLengthLabel.text")); // NOI18N
       historyLengthLabel.setName("historyLengthLabel"); // NOI18N

       selectedColorLabel.setFont(normalFont); // NOI18N
       selectedColorLabel.setText(locResource.getString("selectedColorLabel.text")); // NOI18N
       selectedColorLabel.setName("selectedColorLabel"); // NOI18N

       resetButton.setText(locResource.getString("restartButton.text")); // NOI18N
       resetButton.setName("restartButton"); // NOI18N
       resetButton.addActionListener(new java.awt.event.ActionListener() 
       {
           public void actionPerformed(java.awt.event.ActionEvent evt) 
           {
           		resetBtnPressed();
           }
       });
       
       markedColorButton.setFont(normalFont); // NOI18N
       markedColorButton.setText(locResource.getString("markedColorButton.text")); // NOI18N
       markedColorButton.setName("markedColorButton"); // NOI18N
       markedColorButton.addActionListener(new java.awt.event.ActionListener() 
       {
           public void actionPerformed(java.awt.event.ActionEvent evt) 
           {
           		chooseMarkColor();
           }
       });

       cancelButton.setText(locResource.getString("cancelButton.text")); // NOI18N
       cancelButton.setName("cancelButton");
       cancelButton.addActionListener(new java.awt.event.ActionListener() 
       {
           public void actionPerformed(java.awt.event.ActionEvent evt) 
           {
           		cancelBtnPressed();
           }
       });

       fontSizeLabel.setFont(normalFont); // NOI18N
       fontSizeLabel.setText(locResource.getString("fontSizeLabel.text")); // NOI18N
       fontSizeLabel.setName("fontSizeLabel"); // NOI18N

       viewModeLabel.setFont(normalFont); // NOI18N
       viewModeLabel.setText(locResource.getString("viewModeLabel.text")); // NOI18N
       viewModeLabel.setName("viewModeLabel"); // NOI18N

       fontSizeComboBox.setFont(normalFont); // NOI18N       
       fontSizeComboBox.setName("fontSizeComboBox"); // NOI18N
       setPossibleFontList(fontSizeComboBox);

       javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(innerPanel);
       innerPanel.setLayout(jPanel1Layout);
       jPanel1Layout.setHorizontalGroup(
           jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(jPanel1Layout.createSequentialGroup()
               .addContainerGap()
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                           .addGroup(jPanel1Layout.createSequentialGroup()
                               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                   .addComponent(selectedColorLabel)
                                   .addComponent(historyLengthLabel)
                                   .addComponent(fontSizeLabel)
                                   .addComponent(markedColorLabel)
                                   .addComponent(viewModeLabel))
                               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 53, Short.MAX_VALUE))
                           .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                               .addComponent(cancelButton)
                               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                               .addComponent(resetButton)
                               .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)))
                       .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                           .addComponent(viewModeComboBox, javax.swing.GroupLayout.Alignment.TRAILING, 0, 111, Short.MAX_VALUE)
                           .addComponent(saveButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                           .addComponent(markedColorButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                           .addComponent(historyLengthTextField, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                           .addComponent(selectedColorButton, javax.swing.GroupLayout.Alignment.TRAILING, javax.swing.GroupLayout.DEFAULT_SIZE, 111, Short.MAX_VALUE)
                           .addComponent(fontSizeComboBox, 0, 111, Short.MAX_VALUE)))
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addComponent(canvasSettingTitle)
                       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 204, javax.swing.GroupLayout.PREFERRED_SIZE))
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addComponent(eventsSettingTitle)
                       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 260, javax.swing.GroupLayout.PREFERRED_SIZE))
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addComponent(restartInfoLabel)
                       .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 31, javax.swing.GroupLayout.PREFERRED_SIZE)))
               .addContainerGap())
       );
       jPanel1Layout.setVerticalGroup(
           jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(jPanel1Layout.createSequentialGroup()
               .addContainerGap()
               .addComponent(eventsSettingTitle)
               .addGap(18, 18, 18)
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.CENTER)
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addComponent(historyLengthTextField)
                       .addGap(20, 20, 20)
                       .addComponent(selectedColorButton, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE)
                       .addGap(14, 14, 14)
                       .addComponent(markedColorButton, javax.swing.GroupLayout.DEFAULT_SIZE, 23, Short.MAX_VALUE))
                   .addGroup(jPanel1Layout.createSequentialGroup()
                       .addComponent(historyLengthLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                       .addGap(26, 26, 26)
                       .addComponent(selectedColorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)
                       .addGap(26, 26, 26)
                       .addComponent(markedColorLabel, javax.swing.GroupLayout.PREFERRED_SIZE, 15, javax.swing.GroupLayout.PREFERRED_SIZE)))
               .addGap(21, 21, 21)
               .addComponent(canvasSettingTitle)
               .addGap(18, 18, 18)
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                   .addComponent(fontSizeLabel)
                   .addComponent(fontSizeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
               .addGap(16, 16, 16)
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                   .addComponent(viewModeLabel)
                   .addComponent(viewModeComboBox))
               .addGap(18, 18, 18)
               .addComponent(restartInfoLabel)
               .addGap(26, 26, 26)
               .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                   .addComponent(saveButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                   .addComponent(resetButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                   .addComponent(cancelButton, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
               .addContainerGap())
       );

       javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
       getContentPane().setLayout(layout);
       layout.setHorizontalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
               .addContainerGap()
               .addComponent(innerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
               .addGap(18, 18, 18))
//               .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, javax.swing.GroupLayout.PREFERRED_SIZE))
       );
       layout.setVerticalGroup(
           layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
           .addGroup(layout.createSequentialGroup()
               .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                   .addGroup(layout.createSequentialGroup()
                       .addGap(202, 202, 202))
//                       .addComponent(jFormattedTextField1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                   .addGroup(layout.createSequentialGroup()
                       .addContainerGap()
                       .addComponent(innerPanel, javax.swing.GroupLayout.DEFAULT_SIZE, 349, Short.MAX_VALUE)))
               .addContainerGap())
       );

       pack();
   }
   
   /**
    * Nastavi mnozinu moznych zobrazovacich modu prijatemu
    * comboBoxu
    * 
    * @param box comboBox pro vyber zobrazovaciho modu 
    */
   private void setPossibleViewModes(JComboBox box)
   {
	   String[] list = new String[ViewModeType.class.getEnumConstants().length];
	   ResourceBundle rb = LocalizationUtil.getGeneralResource();
	   
	   int selectedIndex = 0;
	   for(int i = 0; i < list.length; i++)
	   {
		   if(Configuration.getViewMode() == ViewModeType.class.getEnumConstants()[i])
		   {
			   selectedIndex = i;
		   }
		   list[i] = rb.getString(ViewModeType.class.getEnumConstants()[i].toString());
	   }
	   
	   box.setModel(new DefaultComboBoxModel(list));
	   box.setSelectedIndex(selectedIndex);
   }
   
   /**
    * Vrati vybrany zobrazovaci mod
    * @return vybrany zobrazovaci mod
    */
   private ViewModeType getSelectedMode()
   {
	   return ViewModeType.class.getEnumConstants()[viewModeComboBox.getSelectedIndex()];
   }
   
   /**
    * Nastavi mnozinu moznych velikosti pisma prijatemu comboBoxu 
    * @param box comboBox pro vyber velikosti fontu
    */
   private void setPossibleFontList(JComboBox box)
   {
	   String[] list = new String[Configuration.MAX_FONT_SIZE - Configuration.MIN_FONT_SIZE + 1];
	   int selectedIndex = 0;
	   for(int i = 0; i < list.length; i++)
	   {
		   if(Configuration.getFontSize() == Configuration.MIN_FONT_SIZE + i)
		   {
			   selectedIndex = i;
		   }
		   list[i] = "" + (Configuration.MIN_FONT_SIZE + i);
	   }
	   
	   box.setModel(new DefaultComboBoxModel(list));
	   box.setSelectedIndex(selectedIndex);
   }
   
   /**
    * Vrati vybranou velikost pisma
    * @return vybrana velikost pisma
    */
   private int getSelectedFontSize()
   {
	   return fontSizeComboBox.getSelectedIndex() + Configuration.MIN_FONT_SIZE;
   }
   
   /**
    * Osetruje udalost zmacknuti tlaticko pro ulozeni nastaveni. 
    */
   private void saveBtnPressed()
   {
	    historyLengthTextField.setBackground(Color.WHITE);
	   	
	   	if(historyLengthTextField.getText().isEmpty() || 
	   			Integer.parseInt(historyLengthTextField.getText()) <= 0)
	   	{
	   		historyLengthTextField.setBackground(Color.YELLOW);
	   		JOptionPane.showMessageDialog(this, LocalizationUtil.getGeneralResource().getString("dialogs.correctYellow"));
	   		return;
	   	}
	   	
	   	Configuration.setHistoryLength(Integer.parseInt(historyLengthTextField.getText()));
	   	Configuration.setFontSize(getSelectedFontSize());
	   	Configuration.setViewMode(getSelectedMode()); 	   	
	   	
	   	Configuration.setColorOfMarked(tmpMarkColor);
	   	Configuration.setColorOfSelected(tmpSelectColor);
	   	
	   	this.dispose();
   }
   
   /**
    * Osetruje udalost zmacknuti tlaticko pro nacteni defaultniho nastaveni. 
    */
   private void resetBtnPressed()
   {	   
	   fontSizeComboBox.setSelectedIndex(Configuration.DEFAULT_FONT_SIZE - Configuration.MIN_FONT_SIZE);
	   
	   ViewModeType[] vmts = ViewModeType.class.getEnumConstants();
	   for(int i = 0; i < vmts.length; i++ )
	   {
		   if(vmts[i] == Configuration.DEFAULT_VIEW_MODE)
		   {
			   viewModeComboBox.setSelectedIndex(i);
		   }
	   }
   }
   
   /**
    * Osetruje udalost zmacknuti tlaticko pro zruseni. 
    */
   private void cancelBtnPressed()
   {
   		this.dispose();
   }

   /**
    * Vytvori dailog pro vyber barvy vybraneho objektu
    */
   private void chooseSelectColor()
   {
	    Color newColor = JColorChooser.showDialog(this,
	    							 locResource.getString("selectedColorButton.text"),
	                                 tmpSelectColor);
	    if(newColor != null)
	    {
	    	tmpSelectColor = newColor;	    	
	    }
   }
   
   /**
    * Vytvori dailog pro vyber barvy zvyrazneneho objektu
    */
   private void chooseMarkColor()
   {
	    Color newColor = JColorChooser.showDialog(this,
	    							 locResource.getString("selectedColorButton.text"),
	                                 tmpMarkColor);
	    if(newColor != null)
	    {
	    	tmpMarkColor = newColor;	    	
	    }
   }
   
   /**
    * Implementace dokumentu zajistujici kontrolu jeho obsahu, tak
    * aby obsahem bylo pouze cislo urcite delky (poctu
    * znaku - cislic)
    * 
    * @author Matej Prokop, mythge@students.zcu.cz
    */
   class NumericDoc extends PlainDocument 
   {	
	   /**
	    * Maximalni delka obsahu
	    */
	   	private final int MAX_LENGTH;
	   	
	   	/**
	   	 * Vytovri novy objekt kontrolujici delku obsahu
	   	 * @param maxLength maximalni povolena delka obsahu
	   	 */
	   	public NumericDoc(int maxLength)
	   	{
	   		MAX_LENGTH = maxLength;
	   	}
	   	
	   	@Override
	   	public void insertString(int offs, String str, AttributeSet a) throws BadLocationException 
	   	{
	   		if (str == null) 
	   		{
	   			return;
	   		}
	   
	   		// neni prekrocena maximalni delka?
	   		if (MAX_LENGTH - getLength() <= 0) 
	   		{
	   		    return;
	   		}
	   		    		
	   		char[] chars = str.toCharArray();
	   		for(char c : chars)
	   		{
	   			// testuje jsouli vepsane znaky pouze cislice
	   			if(!Character.isDigit(c))
	   			{
	   				return;
	   			}
	   		}
	
	   		// prida do pole obsahu retezce str
	   		super.insertString(offs, new String(chars), a);
	   	}
   }
}
